<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2022-12-21 17:10:12
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\See.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { PropType, reactive, ref, unref, nextTick } from 'vue'

import { ContentWrap } from '@/components/ContentWrap'
import { Descriptions } from '@/components/Descriptions'

import { useTable } from '@/hooks/web/useTableTest'
import { zcMarkOrderDetailedListApi } from '@/api/cy/xMarking'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
import { Folder } from '@element-plus/icons-vue'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
/****************************** 变量 start ******************************/
const dict: any = wsCache.get('dict')

/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})
/****************************** 组件参数 end ******************************/
const searchRef = ref() // 搜索的标签
const breedSubData = ref([]) // 品种的枚举
const dictRelsData = ref() // 联动数据

/****************************** 函数方法 start ******************************/
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}
/****************************** 函数方法 end ******************************/
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcMarkOrderDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 100,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  // {
  //   field: 'customer_code',
  //   label: '牧场编码',
  //   width: 150,
  //   search: {
  //     show: true
  //   }
  // },
  // {
  //   field: 'customer_name',
  //   label: '牧场名称',
  //   width: 150,
  //   search: {
  //     show: true
  //   }
  // },
  {
    field: 'asset_code',
    label: '资产编码',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: false
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: false
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.animal_sex
      },
      show: false
    }
  },
  {
    field: 'month_age',
    label: '月龄',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'purpose',
    label: '用途',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.purpose
      },
      show: false
    }
  }
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 170,
  //   form: {
  //     show: true,
  //     component: 'DatePicker',
  //     componentProps: {
  //       disabled: true,
  //       type: 'datetime',
  //       valueFormat: 'YYYY-MM-DD HH:mm:ss'
  //     }
  //   },
  //   search: {
  //     show: true,
  //     component: 'DatePicker',
  //     componentProps: {
  //       'is-range': true,
  //       'unlink-panels': true,
  //       rangeSeparator: 'To',
  //       type: 'daterange',
  //       valueFormat: 'YYYY-MM-DD HH:mm:ss'
  //     }
  //   }
  // },
  // {
  //   field: 'update_user_name',
  //   label: '创建人',
  //   width: 80,
  //   form: {
  //     show: false
  //   }
  // },
  // {
  //   field: 'action',
  //   width: 60,
  //   fixed: 'right',
  //   label: '操作',
  //   form: {
  //     show: false
  //   },
  //   detail: {
  //     show: false
  //   }
  // }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

/****************************** 初始化 start ******************************/
const newFixedSearch = ref({})
let mark_state = ref('')
const init = async () => {
  // 调用查看接口查询数据
  // await getMedicalOrderSee()
  newFixedSearch.value = {
    mark_order_id: props.currentRow.id
  }
  tableObject.fixedSearch = newFixedSearch.value
  getList()
  mark_state.value = getDictLabel('mark_state', props.currentRow.state)
}
init()

const Formatter = (row, column) => {
  const type = ref('1')
  if (column.property == 'breed') {
    type.value = row.breed
  } else if (column.property == 'breed_sub') {
    type.value = row.breed_sub
  } else if (column.property == 'purpose') {
    type.value = row.purpose
  }
  // console.log('kk', row, column)

  const ss = getDictLabel(column.property, type.value)
  // console.log(ss, 'kk', row, column)
  return ss
}

const animal_sex = (row) => {
  const ss = getDictLabel('animal_sex', row.sex)
  return ss
}

let dsj = ref()

const exportClick = async () => {
  // dsj.value.tableList.push({ name: 'ks' })
  dsj.value = []
  // console.log(Math.ceil(tableObject.count / 10), dsj.value.tableList)
  for (let index = 0; index < Math.ceil(tableObject.count / 10); index++) {
    const { data } = await zcMarkOrderDetailedListApi({
      mark_order_id: props.currentRow.id,
      pageNo: index + 1,
      pageSize: 10
    })
    for (let i = 0; i < data.length; i++) {
      dsj.value.push(data[i])
    }
  }

  //第一个参数是到处后文件名，第二个是id绑定表格dom
  nextTick(() => {
    exportExcel('打标报表', 'mainTable')
  })
}
//转换数据
const exportExcel = (filename, tableId) => {
  var xlsxParam = { raw: true } // 导出的内容只做解析，不进行格式转换
  var table = document.querySelector('#' + tableId).cloneNode(true)
  var wb = XLSX.utils.table_to_book(table, xlsxParam)
  /* 获取二进制字符进行输出 */
  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: true,
    type: 'array'
  })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename + '.xlsx')
  } catch (e) {
    if (typeof console !== 'undefined') {
      console.log(e, wbout)
    }
  }
  return wbout
}
/****************************** 初始化 end ******************************/
</script>

<template>
  <div>
    <el-button
      style="margin-bottom: 20px"
      @click="exportClick"
      type="primary"
      size="small"
      :icon="Folder"
      >导出</el-button
    >

    <ContentWrap title="主数据">
      <Descriptions :schema="props.detailSchema" :data="props.currentRow || {}">
        <template #breed="{ row }: { row: any }">
          <div>{{ getDictLabel('breed', row.breed) }}</div>
        </template>
        <template #breed_sub="{ row }: { row: any }">
          <div>{{ getDictLabel('breed_sub', row.breed_sub) }}</div>
        </template>
        <template #state="{ row }: { row: any }">
          <div>{{ getDictLabel('mark_state', row.state) }}</div>
        </template>
        <template #purpose="{ row }: { row: any }">
          <div>{{ getDictLabel('purpose', row.purpose) }}</div>
        </template>
      </Descriptions>
    </ContentWrap>

    <ContentWrap title="明细数据">
      <Table
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList"
        :loading="tableObject.loading"
        :border="true"
        :pagination="{
          total: tableObject.count
        }"
        @register="register"
        :selection="false"
      />
    </ContentWrap>

    <el-table :data="dsj" style="width: 100%" id="mainTable" v-show="false">
      <el-table-column label="打标报表" align="center">
        <el-table-column :label="`牧场名称：${props.currentRow.pasture_org_name}`" width="150">
          <el-table-column :label="`牧场地址：${props.currentRow.pasture_org_name}`" width="120">
            <el-table-column type="index" label="序号" width="70" />
            <el-table-column prop="enclosure_name" label="栏位" width="120" />
            <el-table-column prop="asset_code" label="资产编码" width="180" />
          </el-table-column>
        </el-table-column>

        <el-table-column :label="`单号：${props.currentRow.code}`">
          <el-table-column :label="`打标申请数量：${props.currentRow.number}`">
            <el-table-column prop="earcon_code" label="耳标" width="120" />
            <el-table-column prop="breed" label="畜别" width="120" :formatter="Formatter" />
            <el-table-column prop="breed_sub" label="品种" width="120" :formatter="Formatter" />
          </el-table-column>
        </el-table-column>

        <el-table-column :label="`打标申请日期：${props.currentRow.create_time}`">
          <el-table-column :label="`打标完成数量：${tableObject.tableList.length}`">
            <el-table-column prop="sex" label="性别" width="120" :formatter="animal_sex" />
            <el-table-column prop="purpose" label="用途" width="120" :formatter="Formatter" />
            <el-table-column label="打标数量" width="100">
              <span>1</span>
            </el-table-column>
          </el-table-column>
        </el-table-column>

        <el-table-column :label="`状态：${mark_state}`" width="50">
          <el-table-column>
            <el-table-column label="状态" width="80">
              <span>{{ mark_state }}</span>
            </el-table-column>
            <el-table-column label="打标日期" width="180">
              <span>{{ props.currentRow.create_time }}</span>
            </el-table-column>
            <el-table-column prop="note" label="备注" width="120" />
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
</template>
